// 导入存储服务
const storageService = require('../../../services/storage')
const playerModeService = require('../../../services/player_mode_service')
// 英文星期缩写映射
const weekdayEnglishMap = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']

const appInstance = getApp();
Page({
  data: {
    // 页面的初始数据
    chartData: null,
    savedCurves: [], // 保存的曲线列表
    pageTitle: '高阶模式', // 页面标题
    pageSubtitle: '自定义RGBW曲线', // 页面副标题
    selectedCurveIndex: -1, // 当前选中的曲线索引，-1表示未选中任何曲线
    weekdayOptions: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'], // 星期选项
    weekdayMap: ['一', '二', '三', '四', '五', '六', '日'], // 中文大写数字映射
    showWeekdayPicker: false, // 控制星期选择器的显示
    currentEditingIndex: -1, // 当前正在编辑星期的曲线索引
    isManualMode: false, // 是否为手动模式


    did: null,
    device: {},
    tmpEnabled: false,
    tmpIndex: -1,
    needChange2Manual: false,
    channels: [],
    origChannels: [],
    mqttData: null,
    editable: true,

    isGroup: false,
    devices: [],
    syncNum: 0,
  },

  onLoad: function (options) {
    console.log(options);
    this.setData({
      did: options.did
    });

    let isGroup = false
    let dobj = storageService.getDeviceInfo(options.did)
    this.data.device = dobj;
    if (dobj.deviceId.startsWith('group_')) {
      isGroup = true
      const devices = storageService.batchGetDeviceInfo(dobj.deviceIds)
      this.data.devices = [...devices]
    }

    let channels = storageService.getDeviceChannels(options.did)
    let newChannels = [];
    channels.forEach(ele => {
      if (ele.u == 1) {
        newChannels.push(ele);
      }
    });
    this.setData({
      channels: newChannels,
      origChannels: channels,
      isGroup: isGroup
    });

    let entityId = options.did
    let deviceType = this.data.device.deviceType

    // 加载保存的曲线数据
    this.loadSavedCurves(entityId, isGroup, deviceType)

    // 检查当前灯光模式状态
    const lightModeState = storageService.getLightModeState(entityId)
    const isManualMode = lightModeState === 'manual'
    this.setData({
      isManualMode
    })

    // 如果是手动模式，关闭所有曲线
    if (isManualMode) {
      this.disableAllCurves()
    }
  },

  onReady: function () {
    // 页面初次渲染完成时执行
    const $t = this;
    if (!this.data.isGroup) {
      wx.$event.on(this.data.device.topicSub, this, (obj) => {
        if (obj.type == "syncDataUp" || obj.type == "chgAutoRun") {
          $t.handleSyncToDeviceDialogResult(1);
        }
      })
    } else {
      this.data.devices.forEach(device => {
        wx.$event.on(device.topicSub, $t, (obj) => {
          if (obj.type == "syncDataUp" || obj.type == "chgAutoRun") {
            $t.handleSyncToDeviceDialogResultGroup(1);
          }
        })
      })
    }
  },

  // 阻止事件冒泡
  stopPropagation: function (e) {
    // 阻止事件冒泡，防止点击弹窗内容时关闭弹窗
    return false
  },

  // 保存曲线数据
  saveCurve: function (index, newStartTime, newEndTime) {
    const chart = this.selectComponent('#rgbwChart')
    if (!chart) {
      this.showToast('获取图表数据失败')
      return
    }

    const curveData = this.data.chartData
    if (!curveData) {
      this.showToast('曲线数据为空')
      return
    }

    // 检查是否有选中的曲线
    const selectedIndex = this.data.selectedCurveIndex
    const isUpdatingExistingCurve =
      selectedIndex >= 0 && selectedIndex < this.data.savedCurves.length

    // 如果没有选中曲线，并且已达到最大保存数量，则提示用户
    if (!isUpdatingExistingCurve && this.data.savedCurves.length >= 7) {
      wx.showModal({
        title: '提示',
        content: '最多保存7组曲线',
        showCancel: false,
      })
      return
    }

    try {
      let updatedCurves = [...this.data.savedCurves]

      if (isUpdatingExistingCurve) {
        // 更新现有曲线
        updatedCurves[selectedIndex].data = JSON.parse(JSON.stringify(curveData)) // 深拷贝曲线数据
        updatedCurves[selectedIndex].createTime = new Date().getTime() // 更新时间戳

        // 更新页面数据
        this.setData({
          savedCurves: updatedCurves,
        })

        this.showToast('曲线已更新', 'success', 400)
      } else {
        // 创建新的曲线
        // 查找空闲的曲线编号（1-7）
        const usedNumbers = new Set()
        this.data.savedCurves.forEach(curve => {
          const match = curve.name.match(/曲线(\d+)/)
          if (match && match[1]) {
            const num = parseInt(match[1])
            if (num >= 1 && num <= 7) {
              usedNumbers.add(num)
            }
          }
        })

        // 找到第一个空闲的编号
        let freeNumber = 1
        for (let i = 1; i <= 7; i++) {
          if (!usedNumbers.has(i)) {
            freeNumber = i
            break
          }
        }

        // 创建新的曲线对象
        const newCurve = {
          name: '曲线' + freeNumber,
          data: JSON.parse(JSON.stringify(curveData)), // 深拷贝曲线数据
          enabled: false,
          createTime: new Date().getTime(),
          weekdays: [false, false, false, false, false, false, false], // 默认不选择任何星期
          hasWeekday: false, // 默认没有选择星期
        }

        // 更新曲线列表
        updatedCurves.push(newCurve)

        // 更新页面数据，并选中新创建的曲线
        this.setData({
          savedCurves: updatedCurves,
          selectedCurveIndex: updatedCurves.length - 1, // 选中新创建的曲线
        })

        this.showToast('保存成功', 'success', 400)
      }

      // 保存到本地存储
      const entityId = this.data.did
      const isGroup = this.data.isGroup
      const deviceType = this.data.device.deviceType
      storageService.saveAdvancedModeData(entityId, {
        curves: updatedCurves
      }, isGroup, deviceType)

      // 保存成功后重置图表为默认状态
      this.resetChart()
    } catch (e) {
      this.showToast('保存失败')
      console.error('保存曲线数据失败', e)
    }
  },
  // 处理图表数据变化
  onChartDataChange: function (e) {
    // 获取图表组件传递的数据
    const {
      chartData
    } = e.detail

    // 更新页面数据
    this.setData({
      chartData: chartData,
    })
    // 如果有选中的曲线，将其启用状态设置为false
    const selectedIndex = this.data.selectedCurveIndex
    if (selectedIndex >= 0 && selectedIndex < this.data.savedCurves.length) {
      const updatedCurves = [...this.data.savedCurves]
      if (updatedCurves[selectedIndex].enabled) {
        updatedCurves[selectedIndex].enabled = false
      }
      updatedCurves[selectedIndex].data = chartData
      this.setData({
        savedCurves: updatedCurves,
      })
      // 保存到本地存储
      const entityId = this.data.did
      const isGroup = 0
      const deviceType = this.data.device.deviceType
      storageService.saveAdvancedModeData(entityId, {
        curves: updatedCurves
      }, isGroup, deviceType)
    }

    // 可以在这里添加实时数据同步到设备的逻辑
    console.log('图表数据已更新', chartData)
  },

  // 加载保存的曲线列表
  loadSavedCurves: function (entityId, isGroup, deviceType) {
    try {
      const advancedModeData = storageService.getAdvancedModeData(entityId, isGroup, deviceType)
      const curves = advancedModeData.curves || []

      // 为每个曲线添加hasWeekday属性
      curves.forEach(curve => {
        if (curve.weekdays) {
          curve.hasWeekday = curve.weekdays.some(day => day === true)
        } else {
          curve.hasWeekday = false
        }
      })

      this.setData({
        savedCurves: curves,
      })
      console.log(`成功加载曲线列表 (ID: ${entityId}, isGroup: ${isGroup})`)
    } catch (e) {
      console.error(`加载保存的曲线列表失败 (ID: ${entityId}, isGroup: ${isGroup})`, e)
      this.setData({
        savedCurves: []
      }) // Set default on error
    }
  },

  // 关闭所有曲线
  disableAllCurves: function () {
    if (!this.data.savedCurves || this.data.savedCurves.length === 0) {
      return
    }

    // 创建曲线列表的副本
    const updatedCurves = [...this.data.savedCurves]

    // 将所有曲线的启用状态设置为false
    let hasChanges = false
    updatedCurves.forEach(curve => {
      if (curve.enabled) {
        curve.enabled = false
        hasChanges = true
      }
    })

    // 如果有变化，更新页面数据并保存到本地存储
    if (hasChanges) {
      this.setData({
        savedCurves: updatedCurves
      })
      const entityId = this.data.did
      const isGroup = this.data.isGroup
      const deviceType = this.data.device.deviceType
      storageService.saveAdvancedModeData(entityId, {
        curves: updatedCurves
      }, isGroup, deviceType)

      // 显示提示信息
      this.showToast('手动模式下，所有曲线已关闭')
    }
  },

  // 保存曲线列表到本地存储
  saveCurvesToStorage: function (entityId, isGroup) {
    if (!entityId) {
      console.error('saveCurvesToStorage: entityId is missing')
      return
    }
    try {
      const deviceType = this.data.device.deviceType
      storageService.saveAdvancedModeData(entityId, {
        curves: this.data.savedCurves
      }, isGroup, deviceType)
      console.log(`成功保存曲线列表 (ID: ${entityId}, isGroup: ${isGroup})`)
    } catch (e) {
      console.error(`保存曲线列表失败 (ID: ${entityId}, isGroup: ${isGroup})`, e)
    }
  },

  // 加载选中的曲线
  loadCurve: function (e) {
    const index = e.currentTarget.dataset.index
    const curve = this.data.savedCurves[index]
    if (!curve) return
    if (this.data.selectedCurveIndex == index) {
      this.resetChart()
      return
    }


    // 获取图表组件实例
    const chartComponent = this.selectComponent('#rgbwChart')
    if (!chartComponent) return

    // 更新图表数据
    chartComponent.setData({
      chartData: JSON.parse(JSON.stringify(curve.data)), // 深拷贝曲线数据
    })

    // 重绘图表
    chartComponent.drawChart()

    // 更新页面数据，并记录当前选中的曲线索引
    this.setData({
      chartData: curve.data,
      selectedCurveIndex: index, // 设置当前选中的曲线索引
      editable: !curve.enabled
    })
  },

  // 编辑曲线名称
  editCurveName: function (e) {
    const index = e.currentTarget.dataset.index
    const curve = this.data.savedCurves[index]
    if (!curve) return

    wx.showModal({
      title: '编辑曲线名称',
      content: '',
      editable: true,
      placeholderText: curve.name,
      success: res => {
        if (res.confirm && res.content) {
          // 更新曲线名称
          const updatedCurves = [...this.data.savedCurves]
          updatedCurves[index].name = res.content

          this.setData({
            savedCurves: updatedCurves,
          })

          // 保存到本地存储
          this.saveCurvesToStorage(this.data.did, this.data.isGroup)
        }
      },
    })
  },

  // 切换曲线启用状态
  toggleCurveEnabled: function (e) {
    const index = e.currentTarget.dataset.index
    const enabled = e.detail.value

    this.data.tmpIndex = index
    this.data.tmpEnabled = enabled

    // 如果是禁用曲线操作
    if (!enabled) {
      this.sendNewSchedule2Device()
      return
    }

    // 检查是否有选中的星期
    const curve = this.data.savedCurves[index]
    if (curve && curve.weekdays) {
      const hasSelectedDay = curve.weekdays.some(day => day === true)
      if (!hasSelectedDay) {
        // 如果没有选中星期，显示提示并重置开关状态
        wx.showModal({
          title: '提示',
          content: '请先选择运行星期后再启用曲线',
          showCancel: false,
        })

        // 重置开关状态为关闭
        const updatedCurves = [...this.data.savedCurves]
        updatedCurves[index].enabled = false

        this.setData({
          savedCurves: updatedCurves,
        })
        return
      }
    }

    // 检查是否有冲突
    const hasConflict = this.checkWeekdayConflict(index)
    if (hasConflict) {
      // 如果有冲突，显示提示并重置开关状态
      wx.showModal({
        title: '提示',
        content: '当前曲线的运行时间与其他曲线存在冲突，无法启用',
        showCancel: false,
      })

      // 重置开关状态为关闭
      const updatedCurves = [...this.data.savedCurves]
      updatedCurves[index].enabled = false

      this.setData({
        savedCurves: updatedCurves,
      })
      return
    }

    // 检查曲线数据的有效性
    if (!curve.data || !this.isValidCurveData(curve.data)) {
      wx.showModal({
        title: '提示',
        content: '曲线数据无效，请重新绘制曲线',
        showCancel: false,
      })

      // 重置开关状态为关闭
      const updatedCurves = [...this.data.savedCurves]
      updatedCurves[index].enabled = false

      this.setData({
        savedCurves: updatedCurves,
      })
      return
    }

    if (enabled) {
      this.sendNewSchedule2Device()
    }
  },
  sendNewSchedule2Device() {
    let mqttMessage = null
    // 发送MQTT消息获取MQTT对象
    mqttMessage = this.prepareMqttScheduleMessage()
    if (mqttMessage == null) { //获取数据失败
      // 更新曲线状态
      const updatedCurves = [...this.data.savedCurves]
      updatedCurves[this.data.tmpIndex].enabled = !this.data.tmpEnabled
      this.setData({
        savedCurves: updatedCurves,
      })
      return
    }
    if (mqttMessage.tls.length == 0) {
      mqttMessage = null
    }

    this.data.needChange2Manual = mqttMessage == null

    // 处理具体的MQTT消息发送
    console.log(`发送高阶模式曲线MQTT消息: ${JSON.stringify(mqttMessage)}`)
    // 实际发送MQTT消息
    const $t = this;
    wx.showLoading({
      title: 'Loading......',
      mask: true,
      success: function () {
        $t.data.mqttData = mqttMessage;
        $t.sendSyncToDeviceDialog(mqttMessage)
      }
    });
  },

  // 检查曲线数据是否有效
  isValidCurveData: function (curveData) {
    if (!curveData) return false

    // 检查所有必需通道是否都有数据
    for (const channel of this.data.channels) {
      // 每个通道至少需要两个点才能形成有效曲线
      if (!Array.isArray(curveData[channel.n]) || curveData[channel.n].length < 2) {
        return false
      }

      // 检查点数据的有效性
      for (const point of curveData[channel.n]) {
        if (typeof point.time !== 'number' || typeof point.brightness !== 'number') {
          return false
        }
      }
    }

    return true
  },

  // 格式化时间时分秒整数形式
  formatTimeForMqtt: function (timeInHours) {
    const hours = Math.floor(timeInHours)
    const minutes = Math.round((timeInHours - hours) * 60)
    const h = hours.toString().padStart(2, '0')
    const m = minutes.toString().padStart(2, '0')
    // 格式化时间为HH:MM格式
    // `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
    return parseInt(h) * 10000 + parseInt(m) * 100;
  },

  // 处理曲线卡片长按事件
  handleCardLongPress: function (e) {
    // 获取点击位置，判断是否在曲线名称区域
    const target = e.target
    if (target && target.dataset && target.dataset.index !== undefined) {
      // 如果是曲线名称区域，已经由editCurveName处理
      return
    }

    // 获取当前卡片索引
    const index = e.currentTarget.dataset.index
    const curve = this.data.savedCurves[index]
    if (!curve) return
    if (curve.enabled) {
      wx.showModal({
        title: '提示',
        content: '启用状态下无法删除!',
        showCancel: false,
      })
      return
    }

    // 显示删除确认对话框
    wx.showModal({
      title: '删除曲线',
      content: `确定要删除曲线"${curve.name}"吗？`,
      success: res => {
        if (res.confirm) {
          // 删除曲线
          const updatedCurves = [...this.data.savedCurves]
          updatedCurves.splice(index, 1)

          this.setData({
            savedCurves: updatedCurves,
          })

          // 保存到本地存储
          this.saveCurvesToStorage(this.data.did, this.data.isGroup)

          this.showToast('已删除曲线', 'success', 400)
        }
      },
    })
  },

  // 重置图表为默认状态
  resetChart: function () {
    // 获取图表组件实例
    const chartComponent = this.selectComponent('#rgbwChart')
    if (!chartComponent) return
    const defaultData = {}
    this.data.channels.forEach(ele => {
      defaultData[ele.n] = [{
          time: 8,
          brightness: 0
        },
        {
          time: 20,
          brightness: 0
        }
      ]
    })

    // 更新图表数据，同时确保应用通道配置
    chartComponent.setData({
      chartData: defaultData,
      activeNodeIndex: -1,
      showDeleteButton: false,
    })

    // 重绘图表
    chartComponent.drawChart()

    // 更新页面数据，并重置选中的曲线索引
    this.setData({
      chartData: defaultData,
      selectedCurveIndex: -1, // 重置选中的曲线索引
      editable: true,
    })
  },

  // 从曲线数据生成计划数据
  generatePlanFromCurveData: function (curveData) {
    if (!curveData) return []
    let $t = this;
    let newData = JSON.parse(JSON.stringify(curveData));
    let allArr = [];
    Object.keys(newData).forEach(function (key) {
      let flag = 0;
      newData[key].forEach(obj => {
        if (obj.brightness != 0) {
          flag = 1;
          return;
        }
      })
      if (flag == 0) {
        allArr.push([]);
      } else {
        let arr = [];
        newData[key].forEach(obj => {
          arr.push([$t.formatTimeForMqtt(obj.time), obj.brightness]);
        })
        allArr.push(arr);
      }
    });
    return allArr;
  },

  // 准备MQTT消息数据但不发送，方便多处调用
  prepareMqttScheduleMessage: function () {
    if (this.data.tmpEnabled) {
      const curve = this.data.savedCurves[this.data.tmpIndex]
      if (!curve || !curve.data) {
        console.error('无效的曲线数据')
        this.showToast('无效的曲线数据')
        return null
      }
      console.log(`曲线原始数据：${JSON.stringify(this.data.savedCurves)}`)

      // 获取星期设置的英文缩写
      const weekdayStr = this.getWeekdayEnglishAbbr(curve.weekdays)
      if (!weekdayStr) {
        console.error('无效的星期设置')
        this.showToast('无效的曲线数据')
        return null
      }
    }

    const tlsArr = []
    let weekIdx = [-1, -1, -1, -1, -1, -1, -1]
    let cloneSavedCurves = JSON.parse(JSON.stringify(this.data.savedCurves));
    cloneSavedCurves[this.data.tmpIndex].enabled = this.data.tmpEnabled
    for (var i = 0; i < cloneSavedCurves.length; i++) {
      const curCurveData = cloneSavedCurves[i]
      if (!curCurveData.enabled) {
        continue;
      }

      console.log("curCurveData", curCurveData)
      const newData = {}
      //处理通道顺序和启停情况
      this.data.origChannels.forEach(ele => {
        let oldData = curCurveData.data[ele.n]
        if (oldData == null) {
          oldData = [{
              "time": 8,
              "brightness": 0
            },
            {
              "time": 20,
              "brightness": 0
            }
          ]
        }
        newData[ele.n] = oldData
      })
      curCurveData.data = newData

      // 准备计划数据
      const plan = this.generatePlanFromCurveData(curCurveData.data)
      const weekdayStr = this.getWeekdayEnglishAbbr(curCurveData.weekdays)
      const curIdx = tlsArr.length;
      tlsArr.push(plan)
      if ("daily" == weekdayStr) {
        weekIdx = [curIdx, curIdx, curIdx, curIdx, curIdx, curIdx, curIdx];
      } else {
        let wArr = weekdayStr.split(",")
        for (var j = 0; j < wArr.length; j++) {
          for (var w = 0; w < 7; w++) {
            if (wArr[j] == weekdayEnglishMap[w]) {
              weekIdx[w] = curIdx
              break;
            }
          }
        }
      }
    }
    return {
      "tls": tlsArr,
      "w": weekIdx
    }
  },

  // 检查星期冲突
  checkWeekdayConflict: function (currentIndex) {
    const currentCurve = this.data.savedCurves[currentIndex]
    if (!currentCurve) return false

    // 检查是否设置为每天运行（所有星期都选中）
    const isAllWeekdays = currentCurve.weekdays && currentCurve.weekdays.every(day => day === true)

    // 如果是每天运行，检查是否有其他已启用的曲线或正在编辑的曲线
    if (isAllWeekdays) {
      return this.data.savedCurves.some(
        (curve, index) =>
        index !== currentIndex && (curve.enabled || index === this.data.currentEditingIndex)
      )
    }

    // 如果不是每天运行，检查是否与其他曲线在星期上有重叠
    return this.data.savedCurves.some((curve, index) => {
      // 跳过自身，但检查所有已启用的曲线或正在编辑的曲线
      if (index === currentIndex) return false
      if (!curve.enabled && index !== this.data.currentEditingIndex) return false

      // 检查两个曲线的星期设置是否有重叠
      return currentCurve.weekdays.some(
        (day, dayIndex) => day && curve.weekdays && curve.weekdays[dayIndex]
      )
    })
  },

  // 打开星期选择器
  openWeekdayPicker: function (e) {
    const index = e.currentTarget.dataset.index
    const curve = this.data.savedCurves[index]
    if (!curve) return

    // 如果曲线没有weekdays属性，初始化为全不选
    if (!curve.weekdays) {
      const updatedCurves = [...this.data.savedCurves]
      updatedCurves[index].weekdays = [false, false, false, false, false, false, false]
      this.setData({
        savedCurves: updatedCurves,
      })
    }
    this.setData({
      showWeekdayPicker: true,
      currentEditingIndex: index,
    })

    /*
    // 获取图表组件实例
    const chartComponent = this.selectComponent('#rgbwChart')
    if (chartComponent && chartComponent.canvas) {
      // 将Canvas转为临时图片，解决弹窗被Canvas遮挡的问题
      wx.canvasToTempFilePath({
        canvas: chartComponent.canvas,
        success: res => {
          // 设置Canvas图片URL并显示图片，同时隐藏Canvas
          chartComponent.setData({
            canvasImageUrl: res.tempFilePath,
            showCanvasImage: true,
            hideCanvas: true,
          })

          // 显示星期选择弹窗
          this.setData({
            showWeekdayPicker: true,
            currentEditingIndex: index,
          })
        },
        fail: err => {
          console.error('Canvas转图片失败:', err)
          // 转换失败时仍然显示弹窗，但不隐藏Canvas
          this.setData({
            showWeekdayPicker: true,
            currentEditingIndex: index,
          })
        },
      })
    } else {
      // 如果无法获取Canvas，直接显示弹窗
      this.setData({
        showWeekdayPicker: true,
        currentEditingIndex: index,
      })
    }*/
  },

  // 关闭星期选择器
  closeWeekdayPicker: function () {
    this.setData({
      showWeekdayPicker: false,
      currentEditingIndex: -1,
    })

    // 保存到本地存储
    this.saveCurvesToStorage(this.data.did, this.data.isGroup)
  },

  // 切换星期选择
  toggleWeekday: function (e) {
    const dayIndex = e.currentTarget.dataset.day
    const curveIndex = this.data.currentEditingIndex

    if (curveIndex < 0 || curveIndex >= this.data.savedCurves.length) return

    if (this.data.savedCurves[curveIndex].enabled) {
      wx.showModal({
        title: '提示',
        content: '请先停用后再更改运行周期。',
        showCancel: false,
        // Material Design 暗色风格
        confirmColor: '#BB86FC',
        confirmText: '我知道了',
      })
      return
    }

    const updatedCurves = [...this.data.savedCurves]
    const weekdays = [...updatedCurves[curveIndex].weekdays]
    weekdays[dayIndex] = !weekdays[dayIndex]

    // 更新星期设置
    updatedCurves[curveIndex].weekdays = weekdays
    // 更新hasWeekday属性
    updatedCurves[curveIndex].hasWeekday = weekdays.some(day => day === true)

    this.setData({
      savedCurves: updatedCurves,
    })

    // 保存到本地存储
    this.saveCurvesToStorage(this.data.did, this.data.isGroup)
  },

  // 获取星期显示文本
  getWeekdaysText: function (weekdays) {
    if (!weekdays || weekdays.length !== 7) {
      return '选择周期'
    }

    // 检查是否全部选中
    const allSelected = weekdays.every(day => day === true)
    if (allSelected) {
      return '每天'
    }

    // 检查是否全部未选中
    const noneSelected = weekdays.every(day => day === false)
    if (noneSelected) {
      return '选择周期'
    }

    // 生成选中星期的文本
    const selectedDays = weekdays
      .map((selected, index) => (selected ? this.data.weekdayMap[index] : ''))
      .filter(day => day !== '')

    return '周' + selectedDays.join('周')
  },

  // 获取星期的英文缩写
  getWeekdayEnglishAbbr: function (weekdays) {
    if (!weekdays || weekdays.length !== 7) {
      return ''
    }

    // 检查是否全部选中
    const allSelected = weekdays.every(day => day === true)
    if (allSelected) {
      return 'daily'
    }

    // 生成选中星期的英文缩写
    const selectedDays = weekdays
      .map((selected, index) => (selected ? weekdayEnglishMap[index] : ''))
      .filter(day => day !== '')

    return selectedDays.join(',')
  },

  sendSyncToDeviceDialog(mqttMessage) {
    const $t = this
    if (!$t.data.isGroup) {
      if (mqttMessage == null) {
        appInstance.sendMtMsg($t.data.device.topicSend, "chgAutoRun", 0);
      } else {
        appInstance.sendMtMsg($t.data.device.topicSend, "syncDataUp", mqttMessage);
      }

      $t.data.timeoutObj = setTimeout(function () {
        $t.handleSyncToDeviceDialogResult(0);
      }, 5000);
    } else {
      $t.data.syncNum = 0
      $t.data.devices.forEach(device => {
        if (mqttMessage == null) {
          appInstance.sendMtMsg(device.topicSend, "chgAutoRun", 0);
        } else {
          appInstance.sendMtMsg(device.topicSend, "syncDataUp", mqttMessage);
        }
      })
      $t.data.timeoutObj = setTimeout(function () {
        $t.handleSyncToDeviceDialogResultGroup(0);
      }, 8000);
    }
  },
  handleSyncToDeviceDialogResult(succ) {
    wx.hideLoading();
    if (succ == 0) {
      wx.showModal({
        title: '提示',
        content: '启用/禁用异常，请求响应超时...',
        showCancel: false,
      })
      const updatedCurves = [...this.data.savedCurves]
      updatedCurves[this.data.tmpIndex].enabled = !this.data.tmpEnabled
      this.setData({
        savedCurves: updatedCurves,
      })
    } else {
      clearTimeout(this.data.timeoutObj);
      const entityId = this.data.did
      const isGroup = 0
      const deviceType = this.data.device.deviceType

      // 更新曲线状态
      const updatedCurves = [...this.data.savedCurves]
      updatedCurves[this.data.tmpIndex].enabled = this.data.tmpEnabled

      this.setData({
        savedCurves: updatedCurves,
        editable: !this.data.tmpEnabled
      })

      //禁用玩家模式和快捷模式
      if (this.data.tmpEnabled) {
        let enableNum = 0
        updatedCurves.forEach(ele => {
          if (ele.enabled) {
            enableNum++
          }
        })
        if (enableNum == 1) {
          const flag = playerModeService.disablePlayerTimerTasks(entityId, isGroup, deviceType)
          if (flag) {
            // 显示提示信息
            wx.showModal({
              title: '提示',
              content: '已启用高阶自动模式，行程自动模式关闭。如需切换行程自动模式，请在行程设置中重新启用。',
              showCancel: false,
              // Material Design 暗色风格
              confirmColor: '#BB86FC',
              confirmText: '我知道了',
            })
          }
        }
      }

      // 切换模式
      storageService.saveLightModeState(entityId, this.data.needChange2Manual ? "manual" : 'auto', isGroup, deviceType)
      this.setData({
        isManualMode: this.data.needChange2Manual,
      })

      const pages = getCurrentPages()
      if (this.data.needChange2Manual) {
        storageService.removeScheduleInfo(entityId)
        pages[0].changeStartEndTimeById(entityId, null)
      } else {
        storageService.saveScheduleInfo(entityId, this.data.mqttData)
        pages[0].changeStartEndTimeById(entityId, this.data.mqttData)
        this.data.mqttData = null;
      }
      // 保存到本地存储
      storageService.saveAdvancedModeData(entityId, {
        curves: updatedCurves
      }, isGroup, deviceType)
    }
  },
  handleSyncToDeviceDialogResultGroup(succ) {
    if (succ == 1) {
      this.data.syncNum++
    }
    if (this.data.syncNum >= this.data.devices.length) {
      this.handleSyncToDeviceDialogResult(1)
      return
    }
    if (succ == 0) {
      if (this.data.syncNum == 0) {
        this.handleSyncToDeviceDialogResult(0)
      } else {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '启用/禁用异常，部分设备失败，请检查设备状态并重新操作。成功' + this.data.syncNum + '台，失败' + (this.data.devices.length - this.data.syncNum) + '台',
          showCancel: false,
        })
        const updatedCurves = [...this.data.savedCurves]
        updatedCurves[this.data.tmpIndex].enabled = !this.data.tmpEnabled
        this.setData({
          savedCurves: updatedCurves,
        })
      }
    }

  },

  showToast(msg, icon = 'none', duration = 1500) {
    wx.showToast({
      title: msg,
      icon: icon,
      duration: duration
    })
  },

  // 应用页面卸载前刷新所有待更新数据
  onUnload: function () {
    const $t = this
    if (!this.data.isGroup) {
      wx.$event.remove(this.data.device.topicSub, this)
    } else {
      this.data.devices.forEach(device => {
        wx.$event.remove(device.topicSub, $t)
      })
    }
  },







})